#!/usr/bin/env python
import tornado.ioloop
import tornado.web
import conf
import datahandler
import json

datahandler = datahandler.DataHandler()
class MainHandler(tornado.web.RequestHandler):
    def initialize(self):
        print 'initialize'
        self.datahandler = datahandler
        self.func_map = {
            'init':self.init_info,
             'get_boats_info':self.get_boats_info,
             'get_map_size':self.get_map_size,
             'begin_game':self.begin_game,
             'ask_begin':self.ask_begin
        }
    def init_info(self, data):
        name = data.get('name', '')
        x = data.get('x', 0)
        y = data.get('y', 0)
        ret = self.datahandler.get_init_data(name, x, y)
        return ret

    def ask_begin(self, data):
        ret = self.datahandler.ask_begin()
        return ret

    def begin_game(self, data):
        ret = self.datahandler.begin_game()
        return ret

    def get_boats_info(self, data):
        ret = self.datahandler.get_boats_info()
        return ret

    def get_map_size(self, data):
        ret = self.datahandler.get_map_size()
        return ret

    def get(self):
        self.write('hello world!')
    def post(self):
        print 'post'
        data = self.request.body
        data = json.loads(data)
        msg = data.get('msg', None)
        if msg:
            func = self.func_map.get(msg, None)
            if func:
                ret = func(data)
                ret = json.dumps(ret)
                self.write(ret)
            else:
                print 'func err'
        else:
            print 'msg err'

application = tornado.web.Application([
    (r'/tengdiver', MainHandler),
])

if __name__ == '__main__':
    application.listen(conf.port)
    tornado.ioloop.IOLoop.instance().start()
